<?php
namespace app\web\home;

use app\common\controller\Common;
use app\lib\model\Price;
use app\web\model\Platform;
use Yansongda\Pay\Pay;
use think\facade\Log;
use app\web\model\Order as myModel;
use app\web\model\User;
use app\web\model\UserBalance;
use app\web\model\UserIntegral;
use app\web\model\Config;
use app\web\model\RechargeStrategy;
use app\web\model\Technician;
use app\web\model\TechnicianBalance;
use app\web\model\Project;
use app\web\model\ShopBalance;
use app\web\model\OrderLogs;
use app\web\model\Scheduling;
use think\Db;


/**
* 
*/
class Paynotify extends Common
{
	
	public function notify(){
        $config = Config::getWechatConfig();
        $wechat = Pay::wechat($config);
        // 是的，验签就这么简单！
        $data = $wechat->verify();
        Log::record("支付回调参数：" . json_encode($data, JSON_UNESCAPED_UNICODE));
        $order_no = $data->out_trade_no;
        // $data['total_fee'] = 21000;
        // $order_no = '2021889577162145792005151';
        $order = myModel::where("order_pay_no", $order_no)->find();



        Log::record("支付回调参数订单：" . json_encode($order));

        if (!empty($order) && $order['pay_status'] != 1) {
            $order->status = 1;
            $order->pay_status = 1;
            $order->pay_money = $data['total_fee']/100;
            $order->pay_time = time();
            Db::startTrans();
            $res = $order->save();
            if(!$res) return 'success';
            $end_time = (int)$order['number']*(int)$order['service_time']+(int)$order['order_time'];
            if($order->integral > 0){
                $res = UserIntegral::change($order->user_id,-$order['integral'],1,$order->id);
                if(!$res){
                    Db::rollback();
                    return 'success';
                }
            }
            
            $technician = Technician::get($order['technician_id']);
            $technician->order_number = (int)$technician->order_number + (int)$order['number'];
            if(!$technician->save()){
                Db::rollback();
                return 'success';
            }
            $project = Project::get($order['project_id']);
            $project->order_number = $project->order_number + (int)$order['number'];
            if(!$project->save()){
                Db::rollback();
                return 'success';
            }
            $user = User::find($order->user_id);
            $change_data = [
                'role' => 0,
                'p_id' => $order->user_id,
                'platform_type' => 1,
                'mobile' => $user->mobile,
                'user_name' => $user->nickName,
                'change_balance' => $order->pay_money,
                'notes' => '用户消费微信支付'
            ];
            if(!Platform::change($change_data)){
                Db::rollback();
                return 'success';
            }
            $order_logs = OrderLogs::create([
                'logs_type' => 1,
                'order_id' => $order->id,
                'contents0' => '通过微信支付完成付款',
                'contents1' => '通过微信支付完成付款',
                'contents2' => '通过微信支付完成付款',
                'mobile' => $order->mobile,
            ]);
            if($order_logs->isEmpty()){
                Db::rollback();
                return 'success';
            }
            Db::commit();
        }
        return 'success';
    }
    /**
     * 加项补差回调
     * [plusorder description]
     * @return [type] [description]
     */
    public function plusorder()
    {
        $config = Config::getWechatConfig();
        $config['notify_url'] = $config['plusorder'];
        $wechat = Pay::wechat($config);
        // 是的，验签就这么简单！
        $data = $wechat->verify();
        Log::record("充值回调参数：" . json_encode($data, JSON_UNESCAPED_UNICODE));
        $plus_pay_no = $data->out_trade_no;
        if($data->return_code == 'SUCCESS'){
            $attach = json_decode($data['attach'],true);
            $plus_money = $data['total_fee']/100;
            $order_id = $attach['order_id'];
            $order = myModel::get($order_id);
            if($order->plus_money > 0) return 'success';
            $order->plus_money = $plus_money;
            $order->tot_money = Price::pricecalc($order->plus_money,'+',$order->tot_money);
            
            Db::startTrans();
            $technician = Technician::field('id,shop_plus_rate,plus_rate')->get($order['technician_id']);
            if($order->shop_id > 0){
                if($technician['shop_plus_rate'] > 0){
                    $order->shop_plus_commission = Price::pricecalc($plus_money,'*',$technician['shop_plus_rate']);
                }
            }
            $order->platform_plus_commission = Price::pricecalc($plus_money,'*',$technician['plus_rate']);
            $order->technician_plus_commission = Price::pricecalc(Price::pricecalc($plus_money,'-',$order->platform_plus_commission),'-',$order->shop_plus_commission);
            $res = $order->save();
            if(!$res){
                Db::rollback();
                return 'success';
            }
            if($order->technician_plus_commission > 0){
                $res = TechnicianBalance::change($order->technician_id,$order->technician_plus_commission,2,'加项补差',$order->id,1);;
                if(!$res){
                    Db::rollback();
                    return 'success';
                }
            }
            if($order->shop_plus_commission > 0){
                $res = ShopBalance::change($order->shop_id,$order->shop_plus_commission,2,'加项补差',$order->id,1);
                if(!$res){
                    Db::rollback();
                    return 'success';
                }
            }
            $user = User::find($order->user_id);
            $change_data = [
                'role' => 0,
                'p_id' => $order->user_id,
                'platform_type' => 2,
                'mobile' => $user->mobile,
                'user_name' => $user->nickName,
                'change_balance' => $plus_money,
                'notes' => '用户加项补差微信支付'
            ];
            if(!Platform::change($change_data)){
                Db::rollback();
                return 'success';
            }
            Db::commit();
            return 'success';
        }
        return 'success';
    }


    /**
     * 充值回调
     * [charge_notify description]
     * @return [type] [description]
     */
    public function recharge()
    {
        $config = Config::getWechatConfig();
        $config['notify_url'] = $config['recharge'];
        $wechat = Pay::wechat($config);
        // 是的，验签就这么简单！
        $data = $wechat->verify();
        Log::record("充值回调参数：" . json_encode($data, JSON_UNESCAPED_UNICODE));

        if($data->return_code == 'SUCCESS'){
            $attach = json_decode($data['attach'],true);
            //充值策略id
            $charge_id = $attach['charge_id'];
            $user_id = $attach['user_id'];


            $charge = RechargeStrategy::get($charge_id);
            $user = User::get($user_id);
            if (!empty($charge) && !empty($user)) {  //充值策略
                $change_balance = Price::pricecalc($charge['give_money'],'+',$charge['recharge_money'],2);
                $after_balance = Price::pricecalc($user->balance,'+',$change_balance,2);
                $add_data = [
                    'user_id' => $user_id,
                    'balance_type' => 0,
                    'before_balance' => $user->balance,
                    'change_balance' => $change_balance,
                    'after_balance' => $after_balance,
                    'strategy_id' => $charge_id,
                    'out_trade_no' => $data['out_trade_no'],
                    'notes' => '充值'.$charge['recharge_money'].'元'.'赠送'.$charge['give_money'].'元'
                ];
                Db::startTrans();
                $res = UserBalance::create($add_data);
                if($res->isEmpty()){
                    Log::record("充值错误:".json_encode($add_data));
                    Db::rollback();
                    return 'success';
                }
                $user->balance = $after_balance;
                if(!$user->save()){
                    Db::rollback();
                    Log::record("充值错误用户余额添加错误".$after_balance);
                    return 'success';
                }
                $change_data = [
                    'role' => 0,
                    'p_id' => $user_id,
                    'platform_type' => 0,
                    'mobile' => $user->mobile,
                    'user_name' => $user->nickName,
                    'change_balance' => $charge['recharge_money'],
                    'notes' => '用户充值',
                ];
                if(!Platform::change($change_data)){
                    Db::rollback();
                    Log::record("充值错误用户余额添加错误11".$after_balance);
                    return 'success';
                }
                Db::commit();
            }
        }
        return 'success';
    }

}

?>